use std::{rc::Rc, cell::RefCell};

use crate::{native, rtda::{Frame, heap::string_pool}, instructions::base};

pub fn init() {
    native::register("sun/misc/VM", "initialize", "()V", initialize);
}

// private static native void initialize();
// ()V
fn initialize(frame: Rc<RefCell<Frame>>) {
    // hack: just make VM.savedProps nonempty
    // unsafe {
    //     let vm_class = frame.borrow().get_method().get_class_ptr();
    //     let saved_props = { &mut *vm_class }.get_ref_var("savedProps", "Ljava/util/Properties;");
    
    //     let loader = {&*vm_class}.get_class_loader().unwrap();
    //     let key = string_pool::j_string(loader, "foo");
    //     let val = string_pool::j_string(loader, "bar");
    
    //     frame.borrow().get_operand_stack().borrow_mut().push_ref(saved_props);
    //     frame.borrow().get_operand_stack().borrow_mut().push_ref(Some(key));
    //     frame.borrow().get_operand_stack().borrow_mut().push_ref(Some(val));

    //     let props_class = { &mut *loader }.load_class("java/util/Properties".to_string());
    //     let set_prop_method = { &*props_class }.get_instance_method("setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;");
    //     base::invoke_method(frame, set_prop_method.unwrap())
    // }

    let class_loader = unsafe { &*frame.borrow().get_method().get_class() }.get_class_loader().unwrap();
    let jl_sys_class = class_loader.lock().unwrap().load_class("java/lang/System".to_string());
    let init_sys_class = unsafe { &*jl_sys_class }.get_static_method("initializeSystemClass", "()V");
    base::invoke_method(frame, init_sys_class.unwrap())
}
